package top.byfree.jbyan.saber.dao

import org.ktorm.dsl.*
import org.springframework.stereotype.Component
import top.byfree.jbyan.saber.bean.Perms
import top.byfree.jbyan.saber.bean.dto.FilterPermDto
import top.byfree.jbyan.saber.bean.pojo.Perm
import top.byfree.jbyan.saber.common.BaseDao
import top.byfree.jbyan.saber.common.coverOrderBy

/**
 * 权限处理Dao
 *
 * @author jbyan
 * @since 27/3/2024
 */
@Component
class PermDao : BaseDao<Perm, Perms>(Perms) {
    fun filter(filterPermDto: FilterPermDto): Query {
        val (permKey, permName, status, gmtCreateStart, gmtCreateEnd, createBy, modifyBy, orderBy) = filterPermDto
        val query = database.from(Perms)
            .select()
            .whereWithConditions { cl ->
                if (!permName.isNullOrBlank()) {
                    cl += Perms.permName like "%$permName%"
                }
                if (!permKey.isNullOrBlank()) {
                    cl += Perms.permKey like "%$permKey%"
                }
                status?.let {
                    cl += Perms.status eq it
                }
                gmtCreateStart?.let {
                    cl += Perms.gmtCreate gte it
                }
                gmtCreateEnd?.let {
                    cl += Perms.gmtCreate lte it
                }
                if (!createBy.isNullOrBlank()) {
                    cl += Perms.createBy like "%$createBy%"
                }
                if (!modifyBy.isNullOrBlank()) {
                    cl += Perms.modifyBy like "%$modifyBy%"
                }
            }

        val coverOrderBy = Perms.coverOrderBy(orderBy)
        // 添加排序
        return coverOrderBy?.let {
            query.orderBy(coverOrderBy)
        } ?: query
    }
}